package com.why.cachecloud.web.service.impl;

import com.why.cachecloud.dao.ConfigDao;
import com.why.cachecloud.entity.SystemConfig;
import com.why.cachecloud.util.ConstUtils;
import com.why.cachecloud.util.StringUtil;
import com.why.cachecloud.web.enums.SuccessEnum;
import com.why.cachecloud.web.service.ConfigService;
import org.apache.commons.collections.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.*;
import java.util.Map.Entry;

/**
 * @Author why
 * @Date 2016年5月23日
 * @Time 上午10:35:26
 */
@Service
public class ConfigServiceImpl implements ConfigService {

    private Logger logger = LoggerFactory.getLogger(ConfigServiceImpl.class);
    @Autowired
    private ConfigDao configDao;


    @PostConstruct
    public void init() {
        reloadSystemConfig();
    }

    /**
     * 加载配置
     */
    @Override
    public void reloadSystemConfig() {
        logger.info("ConfigServiceImpl reload config start");
        // 加载配置
        Map<String, String> configMap = getConfigMap();

        // 联系人配置
        ConstUtils.CONTACT = MapUtils.getString(configMap, "cachecloud.contact");
        logger.debug("{}: {}", "ConstUtils.CONTACT", ConstUtils.CONTACT);

        // 报警相关配置
        // 报警邮件地址
        ConstUtils.EMAILS = MapUtils.getString(configMap, "cachecloud.owner.email");
        logger.debug("{}: {}", "ConstUtils.EMAILS", ConstUtils.EMAILS);

        // 报警电话
        ConstUtils.PHONES = MapUtils.getString(configMap, "cachecloud.owner.phone");
        logger.debug("{}: {}", "ConstUtils.PHONES", ConstUtils.PHONES);

        // 报警钉钉
        ConstUtils.DINGTALK = MapUtils.getString(configMap, "cachecloud.owner.dingtalk");
        logger.debug("{}: {}", "ConstUtils.DINGTALK", ConstUtils.DINGTALK);

        // ssh相关配置
        // ssh username
        ConstUtils.USERNAME = MapUtils.getString(configMap, "cachecloud.machine.ssh.name", ConstUtils.DEFAULT_USERNAME);
        logger.debug("{}: {}", "ConstUtils.USERNAME", ConstUtils.USERNAME);

        // ssh password
        ConstUtils.PASSWORD = MapUtils.getString(configMap, "cachecloud.machine.ssh.password",
                ConstUtils.DEFAULT_PASSWORD);
        logger.debug("{}: {}", "ConstUtils.PASSWORD", ConstUtils.PASSWORD);

        // ssh 端口
        ConstUtils.SSH_PORT_DEFAULT = Integer.parseInt(MapUtils.getString(configMap, "cachecloud.machine.ssh.port",
                String.valueOf(ConstUtils.DEFAULT_SSH_PORT_DEFAULT)));
        logger.debug("{}: {}", "ConstUtils.SSH_PORT_DEFAULT", ConstUtils.SSH_PORT_DEFAULT);

        //ssh授权方式
        ConstUtils.SSH_AUTH_TYPE = MapUtils.getIntValue(configMap, "cachecloud.ssh.auth.type", ConstUtils.DEFAULT_SSH_AUTH_TYPE);
        logger.debug("{}: {}", "ConstUtils.SSH_AUTH", ConstUtils.SSH_AUTH_TYPE);

        //public key pem
        ConstUtils.PUBLIC_KEY_PEM = MapUtils.getString(configMap, "cachecloud.public.key.pem", ConstUtils.DEFAULT_PUBLIC_KEY_PEM);
        logger.debug("{}: {}", "ConstUtils.PUBLIC_KEY_PEM", ConstUtils.PUBLIC_KEY_PEM);

        // ssh key username
        ConstUtils.PUBLIC_USERNAME = MapUtils.getString(configMap, "cachecloud.public.user.name", ConstUtils.DEFAULT_PUBLIC_USERNAME);
        logger.debug("{}: {}", "ConstUtils.PUBLIC_USERNAME", ConstUtils.PUBLIC_USERNAME);

        // 管理员相关配置
        // 管理员name
        ConstUtils.SUPER_ADMIN_NAME = MapUtils.getString(configMap, "cachecloud.admin.user.name",
                ConstUtils.DEFAULT_SUPER_ADMIN_NAME);
        logger.debug("{}: {}", "ConstUtils.SUPER_ADMIN_NAME", ConstUtils.SUPER_ADMIN_NAME);

        // 管理员password
        ConstUtils.SUPER_ADMIN_PASS = MapUtils.getString(configMap, "cachecloud.admin.user.password",
                ConstUtils.DEFAULT_SUPER_ADMIN_PASS);
        logger.debug("{}: {}", "ConstUtils.SUPER_ADMIN_PASS", ConstUtils.SUPER_ADMIN_PASS);

        // 超级用户组
        ConstUtils.SUPER_ADMINS = MapUtils.getString(configMap, "cachecloud.superAdmin",
                ConstUtils.DEFAULT_SUPER_ADMINS);
        logger.debug("{}: {}", "ConstUtils.SUPER_ADMINS", ConstUtils.SUPER_ADMINS);

        // 超级管理员
        ConstUtils.SUPER_MANAGER = Arrays.asList(ConstUtils.SUPER_ADMINS.split(","));
        logger.debug("{}: {}", "ConstUtils.SUPER_MANAGER", ConstUtils.SUPER_MANAGER);

        // 管理员电话
        String adminMobile = MapUtils.getString(configMap, "cachecloud.admin.user.mobile");
        if (!StringUtil.isBlank(adminMobile)) {
            ConstUtils.SUPER_MANAGER_MOBILE = Arrays.asList(adminMobile.split(","));
            logger.debug("{}: {}", "ConstUtils.SUPER_MANAGER_MOBILE", ConstUtils.SUPER_MANAGER_MOBILE);
        }
        // 领导邮箱
        String leaderEmailListStr = MapUtils.getString(configMap, "cachecloud.leader.email");
        if (!StringUtil.isBlank(leaderEmailListStr)) {
            ConstUtils.LEADER_EMAIL_LIST = Arrays.asList(leaderEmailListStr.split(","));
        }

        // 机器内存报警阀值
        ConstUtils.MEMORY_USAGE_RATIO_THRESHOLD = MapUtils.getDoubleValue(configMap, "machine.mem.alert.ratio",
                ConstUtils.DEFAULT_MEMORY_USAGE_RATIO_THRESHOLD);
        logger.debug("{}: {}", "ConstUtils.MEMORY_USAGE_RATIO_THRESHOLD", ConstUtils.MEMORY_USAGE_RATIO_THRESHOLD);


        ConstUtils.COOKIE_DOMAIN = MapUtils.getString(configMap, "cachecloud.cookie.domain", ConstUtils.DEFAULT_COOKIE_DOMAIN);

        //cachecloud根目录
        ConstUtils.CACHECLOUD_BASE_DIR = MapUtils.getString(configMap, "cachecloud.base.dir", ConstUtils.DEFAULT_CACHECLOUD_BASE_DIR);
        logger.debug("{}: {}", "ConstUtils.CACHECLOUD_BASE_DIR", ConstUtils.CACHECLOUD_BASE_DIR);

        //应用客户端连接报警阀值
        ConstUtils.APP_CLIENT_CONN_THRESHOLD = MapUtils.getIntValue(configMap, "cachecloud.app.client.conn.threshold", ConstUtils.DEFAULT_APP_CLIENT_CONN_THRESHOLD);
        logger.debug("{}: {}", "ConstUtils.APP_CLIENT_CONN_THRESHOLD", ConstUtils.APP_CLIENT_CONN_THRESHOLD);

        //邮件报警接口
        ConstUtils.EMAIL_ALERT_INTERFACE = MapUtils.getString(configMap, "cachecloud.email.alert.interface");
        logger.debug("{}: {}", "ConstUtils.EMAIL_ALERT_INTERFACE", ConstUtils.EMAIL_ALERT_INTERFACE);

        //短信报警接口
        ConstUtils.MOBILE_ALERT_INTERFACE = MapUtils.getString(configMap, "cachecloud.mobile.alert.interface");
        logger.debug("{}: {}", "ConstUtils.MOBILE_ALERT_INTERFACE", ConstUtils.MOBILE_ALERT_INTERFACE);

        //钉钉报警接口
        ConstUtils.DING_TALK_ALERT_INTERFACE = MapUtils.getString(configMap, "cachecloud.dingTalk.alert.interface");
        logger.debug("{}: {}", "ConstUtils.DING_TALK_ALERT_INTERFACE", ConstUtils.DING_TALK_ALERT_INTERFACE);
        ConstUtils.DING_TALK_ACCESS_TOKEN = MapUtils.getString(configMap, "cachecloud.dingTalk.alert.access.token");
        logger.debug("{}: {}", "ConstUtils.DING_TALK_ACCESS_TOKEN", ConstUtils.DING_TALK_ACCESS_TOKEN);
        ConstUtils.DING_TALK_SECRET = MapUtils.getString(configMap, "cachecloud.dingTalk.alert.secret");
        logger.debug("{}: {}", "ConstUtils.DING_TALK_SECRET", ConstUtils.DING_TALK_SECRET);

        //是否定期清理各种统计数据(详见CleanUpStatisticsJob)
        ConstUtils.WHETHER_SCHEDULE_CLEAN_DATA = MapUtils.getBooleanValue(configMap, "cachecloud.whether.schedule.clean.data", ConstUtils.DEFAULT_WHETHER_SCHEDULE_CLEAN_DATA);
        logger.debug("{}: {}", "ConstUtils.WHETHER_SCHEDULE_CLEAN_DATA", ConstUtils.WHETHER_SCHEDULE_CLEAN_DATA);

        // 机器性能统计周期(分钟)
        ConstUtils.MACHINE_STATS_CRON_MINUTE = MapUtils.getIntValue(configMap, "cachecloud.machine.stats.cron.minute", ConstUtils.DEFAULT_MACHINE_STATS_CRON_MINUTE);
        logger.debug("{}: {}", "ConstUtils.MACHINE_STATS_CRON_MINUTE", ConstUtils.MACHINE_STATS_CRON_MINUTE);

        logger.info("ConfigServiceImpl reload config end");
    }

    @Override
    public SuccessEnum updateConfig(Map<String, String> configMap) {
        for (Entry<String, String> entry : configMap.entrySet()) {
            String configKey = entry.getKey();
            String configValue = entry.getValue();
            try {
                configDao.update(configKey, configValue);
            } catch (Exception e) {
                logger.error("key {} value {} update faily" + e.getMessage(), configKey, configValue, e);
                return SuccessEnum.FAIL;
            }
        }
        return SuccessEnum.SUCCESS;
    }

    @Override
    public List<SystemConfig> getConfigList(int status) {
        try {
            return configDao.getConfigList(status);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return Collections.emptyList();
        }
    }

    /**
     * 获取所有配置的key-value
     *
     * @return
     */
    private Map<String, String> getConfigMap() {
        Map<String, String> configMap = new LinkedHashMap<>();
        // 获取有效系统配置 status 1：有效 0：无效
        List<SystemConfig> systemConfigList = getConfigList(1);
        for (SystemConfig systemConfig : systemConfigList) {
            configMap.put(systemConfig.getConfigKey(), systemConfig.getConfigValue());
        }
        return configMap;
    }

}
